#!/usr/bin/python3
# -*- coding: utf-8 -*-
"""
Attributes:
    __version__ (str): "0.0.1"
    __copyright__ (str): "Copyright (C) 2025 z"
    __license__ (str): "MIT"
    __author__ (str): "Z"
"""

from flask import request, jsonify

from wingman import db_enter, logger
from wingman.common.error import ErrorCode
from wingman.cicd.jenkins import JenkinsMap
from wingman.ai.openrouter import CustomAI
from wingman.cloud.aliyun import Business
from config.rules_help import (TALKROBOT_HELP, CICD_HELP, ALIYUN_HELP)


class Event:
    """钉钉/飞书,CICD/AI及其它用于机器人回调功能"""

    def _get_parameter(self, parameter: list, count: int) -> list:
        """获取参数,确保返回的参数数量符合要求"""
        return parameter[0:0 + count] if len(parameter) >= count else []

###############################################################
    def _slice_content(self, message) -> list:
        """
        # 分析消息,返回命令数组, 数组=0则不是有效输入
        切片 message['text']['content']
        :param message: cicd www
        :return: ['cicd', 'www']
        """
        content = message['text']['content'].strip()  # 去除前后空格
        parts = content.split()                       # 将内容分割为多个部分
        content = [word.strip() for word in parts]    # 去除每个单词的前后空格
        return content
##############################################################

    def distribute(self) -> dict:
        """
        分发到相应的功能
        :return: content
        """
        message = request.get_json()
        # source_client_ip = request.remote_addr
        # function_name = inspect.currentframe().f_code.co_name  # 获取当前函数名称
############################################################
        # 处理指命list,调用对应方法
        funarr = self._slice_content(message)
        try:
            if len(funarr) > 1:
                if funarr[0] in TALKROBOT_HELP:
                    if funarr[0]:
                        parameter = []
                        for i in range(1, len(funarr), 1):
                            parameter.append(funarr[i])
                        content =  eval(TALKROBOT_HELP[funarr[0]][0])(parameter)
                        if isinstance(content, dict):
                            content.update({"customize_env": f"{parameter[0]}"})
                        else:
                            logger.warning(ErrorCode.WARNING_DISTRIBUTE.value, content, __name__)
                    else:
                        content = self.to_help()
                else:
                    content = self.to_help()
            else:
                content = self.to_help()
        except Exception as e:
            logger.error(ErrorCode.ROBOT_DISTRIBUTE.value, str(e), __name__)
            return self.to_ai(funarr)

        logger.info(ErrorCode.SUCCESS.value, content, __name__)
        return content

    def to_help(self) -> dict:
        """获取帮助消息 回复 可用命令消息"""
        return {
            "result_msg": "".join(
                "- @bot " + str(key) + " : 作用 : " + str(value[2]) + "\n"
                for key, value in TALKROBOT_HELP.items()
            )
        }

    def to_jenkins(self, parameter: list = None) -> dict:
        """Jenkins处理"""
        try:
            env_name, task = self._get_parameter(parameter, 2)
            result = JenkinsMap().getcode_jenkins(env_name, task)
            if result is None:
                result = {
                    "result_msg": "".join(
                        "- @bot [空格] cicd [空格] " + "[环境名] [空格] " + f"{key} [回车] 部署对应环境项目"+ "\n"
                        for key in CICD_HELP
                    )
                }
        except Exception as e:
            result = {
                "result_msg": "".join(
                    "- @bot [空格] cicd [空格] " + "[环境名] [空格] " + f"{key} [回车] 部署对应环境项目"+ "\n"
                    for key in CICD_HELP
                )
            }
            logger.warning(ErrorCode.TOJENKINS.value, result, __name__)
        finally:
            return result

    def to_aliyun(self, parameter: list = None) -> dict:
        """aliyun接口"""
        try:
            task, data = self._get_parameter(parameter, 2)
            business = Business()
            result = business(task.strip(), data.strip())
        except Exception:
            result = {"result_msg": "".join(f"- @bot [空格] aliyun [空格] {key} [空格] {value} \n" for key, value in ALIYUN_HELP.items())}
            logger.warning(ErrorCode.TOJENKINS.value, result, __name__)
        finally:
            return result

    def to_ai(self, parameter: list = None) -> dict:
        """AI处理"""
        try:
            result = {"result_msg": CustomAI().llm(' '.join(parameter).replace('"', ''))}
        except Exception as e:
            result = {"result_msg": f"{str(e)}"}
            logger.error(ErrorCode.ROBOT_TO_AI.value, result, __name__)
        finally:
            return result


if __name__ == '__main__':
    dispatch = Event().distribute
    message = {
        "senderPlatform": "Win",
        "conversationId": "cid1vhk2zgquXZfLWQ+xlQ7vQ==",
        "atUsers": [{"dingtalkId": "$:LWCP_v1:$JkTXMFILsZdfSvh5tgzAe7VBTx6l0+DV"}],
        "chatbotCorpId": "ding05ab5b83a227d629acaaa37764f00000",
        "chatbotUserId": "$:LWCP_v1:$JkTXMFILsZdfSvh5tgzAe7VBTx6l0+SS",
        "msgId": "msgOVsk+HoCV4ymtO/9rah2ds==",
        "senderNick": "用户名子",
        "isAdmin": "True",
        "senderStaffId": "manager1111",
        "sessionWebhookExpiredTime": 1740655631111,
        "createAt": 1740650231111,
        "senderCorpId": "ding05ab5b83a227d629acaaa37764f11111",
        "conversationType": "2",
        "senderId": "$:LWCP_v1:$4Bd2dS2AdL4UjPVPWOKdLd==",
        "conversationTitle": "群名子",
        "isInAtList": "True",
        "sessionWebhook": "https://oapi.dingtalk.com/robot/sendBySession?session=c7ec89457dd9395d21d47a1906asdf11",
        "text": {
            "content": " cicd test www"
        },
        "robotCode": "dingsirtwamjummest00",
        "msgtype": "text"
    }
    dispatch(message)
